package com.adee.gulimall.product.service.impl;

import com.adee.gulimall.common.utils.PageUtils;
import com.adee.gulimall.common.utils.Query;
import com.adee.gulimall.product.dao.SkuInfoDao;
import com.adee.gulimall.product.entity.SkuImagesEntity;
import com.adee.gulimall.product.entity.SkuInfoEntity;
import com.adee.gulimall.product.entity.SpuInfoDescEntity;
import com.adee.gulimall.product.service.*;
import com.adee.gulimall.product.vo.SkuItemSaleAttrVo;
import com.adee.gulimall.product.vo.SkuItemVo;
import com.adee.gulimall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)) {
            wrapper.and(w -> {
                w.eq("publish_status", status);
            });
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.and(w -> {
                w.eq("brand_id", brandId);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.and(w -> {
                w.eq("catalog_id", catelogId);
            });
        }
        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)) {
            try {
                // 客户端传来的min可能不规范，不是数字，需要try-catch
                BigDecimal m = new BigDecimal(min);
                if(m.compareTo(new BigDecimal("0")) == 1) {
                    wrapper.and(w -> {
                        w.ge("price", min);
                    });
                }
            } catch (Exception e) {
                log.error("min 转为 BigDecimal错误：{}", min);
            }
        }
        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)) {
            try {
                BigDecimal m = new BigDecimal(max);
                if(m.compareTo(new BigDecimal("0")) == 1) {
                    wrapper.and(w -> {
                        w.le("price", max);
                    });
                }
            } catch (Exception e) {
                log.error("max 转为 BigDecimal错误：{}", max);
            }
        }
        return new PageUtils(page);
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo vo = new SkuItemVo();
        // 1. sku基本信息 pms_sku_info
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = getById(skuId);
            vo.setInfo(info);
            return info;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrsFuture = infoFuture.thenAcceptAsync(res -> {
            // 3. spu销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            vo.setSaleAttr(saleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> spuInfoDescFuture = infoFuture.thenAcceptAsync(res -> {
            // 4. spu介绍 pms_spu_info_desc
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(res.getSpuId());
            vo.setDesc(spuInfoDesc);
        }, threadPoolExecutor);

        CompletableFuture<Void> groupFuture = infoFuture.thenAcceptAsync(res -> {
            // 5. spu规格参数信息
            // 获取当前商品的所有分组即各分组下的属性值
            List<SpuItemAttrGroupVo> groupVo = attrGroupService
                    .getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            vo.setGroupAttrs(groupVo);
        }, threadPoolExecutor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(()->{
            // 2. sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            vo.setImages(images);
        });

        // 等待所有任务都完成
        CompletableFuture.allOf(saleAttrsFuture, spuInfoDescFuture, groupFuture, imagesFuture).get();

        return vo;
    }

}